<template>
  <div class="container">
    <div class="top">
      <div>
        <span>
          <span>区段：&nbsp;&nbsp;</span>
          <el-tree-select v-model="searchData.oneGridId" :data="dataSource"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange">
          </el-tree-select>
        </span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <span>
          <span>工区：&nbsp;&nbsp;</span>
          <el-tree-select v-model="searchData.twoGridId" :data="dataSourceArea"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly>
          </el-tree-select>
        </span>&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="primary" plain @click="search">查询</el-button>
        <el-button type="primary" plain @click="resetSearch">重置</el-button>
      </div>
      <div>
        <el-button type="primary" @click="handleImport">导入</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="add">新增</el-button>
      </div>
      
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" height="calc(100% - 20px)">
      <el-table-column type="index" label="序号" width="55"> </el-table-column>
      <el-table-column prop="oneGrid" label="一级网格单位"> </el-table-column>
      <el-table-column prop="twoGrid" label="二级网格单位"> </el-table-column>
      <el-table-column prop="responsibility" label="责任范围"> </el-table-column>
      <el-table-column prop="gridLeader" label="网格组长"> </el-table-column>
      <el-table-column prop="gridOperator" label="网格员"> </el-table-column>
      <el-table-column prop="date" label="操作">
        <template #default="scope">
          <el-icon title="编辑" @click="edit(scope.row)">
            <Edit />
          </el-icon>
          &nbsp;
          <el-icon title="删除" @click="del(scope.row)">
            <Delete />
          </el-icon>
        </template> </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog title="抢险队伍管理" v-model="open" width="500px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="一级网格单位" prop="oneGridId">
          <el-tree-select v-model="form.oneGridId" :data="dataSource"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="二级网格单位" prop="twoGridId">
          <el-tree-select v-model="form.twoGridId" :data="dataSourceArea"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange2">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="网格组长" prop="gridLeader">
          <el-select v-model="form.gridLeader" placeholder="请选择" clearable
            >
            <el-option v-for="item in personList" :key="item.userId" :label="item.userName" :value="item.userName" />
          </el-select>
        </el-form-item>
        <el-form-item label="网格员" prop="gridOperator">
          <el-select v-model="form.gridOperators" placeholder="请选择" clearable multiple
            >
            <el-option v-for="item in personList" :key="item.userId" :label="item.userName" :value="item.userName" />
          </el-select>
        </el-form-item>
        <el-form-item label="责任范围" prop="responsibility">
          <el-input type="textarea" v-model="form.responsibility" placeholder="请输入责任范围" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    getGrid,
    delGrid,
    addGrid,
    editGrid,
    getDeptBy,
    getTreeList,
    getPersonBy
  } from "@/api/work";
  const {
    proxy
  } = getCurrentInstance();
  const personList = ref([])
  const all = ref([])
  //获取人员数据
  function getPerson(id) {
    getPersonBy({deptId: id}).then(res => {
      personList.value = res.rows
      all.value = JSON.parse(JSON.stringify(res.rows))
    })
  }
  // getPerson()


  //区段数据
  const dataSource = ref([])
  const dataSourceArea = ref([])

  function getTree() {
    getTreeList().then(res => {
      dataSource.value = res.data
    })
  }
  getTree()

  function treeChange(id) {
    searchData.value.twoGridId = ''
    form.value.gridOperators = []
    personList.value = []
    form.value.gridLeader = ''
    form.value.twoGridId = ''
    getDeptBy({
      parentId: id
    }).then(res => {
      dataSourceArea.value = res.data
    })
  }
  function treeChange2(id) {
    form.value.gridOperators = []
    personList.value = []
    form.value.gridLeader = ''
    form.value.twoGridId = id
    getPerson(id)
  }

  const open = ref(false)
  const searchData = ref({
    oneGridId: '',
    twoGridId: ''
  })

  function search() {
    getGrid(searchData.value).then(res => {
      tableData.value = res.rows
    })
  }
  function resetSearch(){
    searchData.value = {
      oneGridId: '',
      twoGridId: ''
    }
    getList()
  }

  const tableData = ref([])
  const loading = ref(true);
  function getList() {
    loading.value = true
    getGrid().then(res => {
      loading.value = false
      tableData.value = res.rows
    })
  }
  getList()

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      postCode: undefined,
      postName: undefined,
      phone: undefined
    },
    rules: {
      phone: [{
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }],
      // postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
      // postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
      // postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
    }
  });
  const {
    queryParams,
    form,
    rules
  } = toRefs(data);

  function edit(row) {
    dataSourceArea.value = []
    personList.value = []
    getDeptBy({
      parentId: row.oneGridId
    }).then(res => {
      dataSourceArea.value = res.data
    })
    if(row.twoGridId){
      getPerson(row.twoGridId)
    }
    if(row.gridOperator != ""){
      row.gridOperators = row.gridOperator.split(",")
    }else{
      row.gridOperators = []
    }
    form.value = row
    open.value = true
  }

  function add() {
    form.value = {}
    open.value = true
    dataSourceArea.value = []
    personList.value = []
  }
  
  import { getToken } from '@/utils/auth'
  /*** 导入参数 */
  const upload = reactive({
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '',
      // 是否禁用上传
      isUploading: false,
      // 是否更新已经存在的用户数据
      updateSupport: 0,
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + getToken() },
      // 上传的地址
      url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/gridManage/importData',
  })
  /** 导入按钮操作 */
  function handleImport() {
      upload.title = '导入'
      upload.open = true
  }
  /**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}
  /** 提交上传文件 */
function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
}
  /** 下载模板操作 */
  function importTemplate() {
      proxy.download('sjgtw-emergency/gridManage/downloadTemplate', {}, `template_${new Date().getTime()}.xlsx`)
  }
  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
      upload.open = false
      upload.isUploading = false
      proxy.$refs['uploadRef'].handleRemove(file)
      if (response.code == 200) {
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      } else {
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入失败', { dangerouslyUseHTMLString: true })
      }
      getList()
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("sjgtw-emergency/gridManage/export", {
      ...queryParams.value, 
    }, `防洪网格化管理${new Date().getTime()}.xlsx`);
  }

  function del(data) {
    ElMessageBox.confirm(
        '确认删除吗？',
        'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        delGrid(data.id).then(res => {
          ElMessage({
            type: 'success',
            message: '已删除',
          })
          getList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }

  function cancel() {
    open.value = false
  }

  function submitForm() {
    proxy.$refs["postRef"].validate(valid => {
      if (valid) {
        form.value.gridOperator = form.value.gridOperators.join(",")
        if (form.value.id != undefined) {
          editGrid(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList()
          });
        } else {
          addGrid(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList()
          });
        }
      }
    });
  }
</script>

<style lang='scss' scoped>
  .container {
    height: 100%;
    width: 100%;
    padding: 20px;
  }

  .top {
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: space-between;
  }

  .end {
    justify-content: flex-end;
  }

  :deep(.el-table .el-table__cell) {
    text-align: center;
  }
  :deep(.el-table--border::before) {
    width: 0px;;
  }
  :deep(.el-table--border::after) {
    width: 0px;;
  }
</style>